package com.hebeiboruan.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hebeiboruan.common.exception.system.user.UserException;
import com.hebeiboruan.common.exception.system.user.UserResultEnum;
import com.hebeiboruan.entity.system.Power;
import com.hebeiboruan.entity.system.User;
import com.hebeiboruan.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.hebeiboruan.user.service.UserService;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用户业务类
 * @author 刘焕林
 * @date 2023/11/02
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Value("${project.staticPath}")
    private String staticPath;
    @Value("${project.verificationCode}")
    private String verificationCode;
    private RedisTemplate redisTemplate;
    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public User getUser(String account) {
        return getOne(new QueryWrapper<User>().eq("user_account", account));
    }

    @Override
    public User Login(String account, String password) {
        User user=getUser(account);
        if(user==null){
            throw new UserException(UserResultEnum.ACCOUNT_IS_NULL);
        }
        if(!password.equals(user.getUserPassword())){
        throw new UserException(UserResultEnum.PASSWORD_ERROR);
        }
        return user;
    }

    @Override
    public String getVerificationCodeValue(String verificationCode) {
        if(!redisTemplate.hasKey(verificationCode)){
            return null;
        }
        return redisTemplate.opsForValue().get(verificationCode).toString();
    }

    @Override
    public void insertVerificationCode(String verificationCode, String value) {
        redisTemplate.opsForValue().set(verificationCode,value);
        redisTemplate.expire(value,300, TimeUnit.SECONDS);
    }



    @Override
    public List<Power> getUserPower(Integer userNo) {
        return baseMapper.getUserPower(userNo);
    }

    @Override
    @Scheduled(cron = "0 0 2 * * ?")
    public void clear() throws IOException {
        Path path= Paths.get(staticPath+"/"+verificationCode+"/");
        for (File file: path.toFile().listFiles()
             ) {
            file.delete();
        }

    }
}
